package com.studydemo.config;

import com.studydemo.filter.JwtAuthenticationTokenFilter;
import com.studydemo.service.SysUserService;
import com.studydemo.utils.CustomPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;

@Configuration
@EnableWebSecurity
public class SecurityConfig{
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new CustomPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http)throws Exception{
        //每次都需要认证 不需要session 会话管理策略设置为无状态，这样就可以防止应用程序的会话被劫持攻击。
        http.sessionManagement(Customizer.withDefaults());
        //每次都需要认证 不需要session 会话管理策略设置为无状态，这样就可以防止应用程序的会话被劫持攻击。
        http.sessionManagement(Customizer.withDefaults());
        //禁用表单登录 前后分离用不上
        http.formLogin().disable();
        http
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.authorizeHttpRequests(authorizeHttpRequests->
                authorizeHttpRequests.requestMatchers("/login/in","/login/on").permitAll()

                        .anyRequest().authenticated()
        );
        http.csrf().disable(); //跨域漏洞防御:关闭
        http.cors().disable(); //跨域拦截关闭
        return http.build();
    }

    @Bean
    public HttpFirewall httpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedDoubleSlash(true); // 允许双斜杠
        return firewall;
    }

    /**
     * 把认证管理器注入到容器
     * LoginServiceImpl类中 才能使用这个认证接口
     * @param config
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
}
